# -*- coding: utf-8 -*-
from __future__ import annotations

from dataclasses import dataclass
from datetime import datetime
from typing import Any, Dict

from common.base_enums import EventType


@dataclass(frozen=True)
class DomainEvent:
	event_type: str
	payload: Dict[str, Any]
	alarm_id: int | None = None
	msg_id: str | None = None
	meter_code: str | None = None
	created_at: datetime = datetime.utcnow()


@dataclass(frozen=True)
class AlarmRaisedEvent(DomainEvent):
	def __init__(self, alarm_id: int, msg_id: str, meter_code: str, alarm_type: str, rule_name: str = '', **payload: Any):
		"""告警产生事件

		Args:
			alarm_id: 告警ID
			msg_id: 消息ID
			meter_code: 电表编码
			alarm_type: 告警类型
			rule_name: 规则名称
			**payload: 其他负载数据
		"""
		# 构造完整的payload，确保包含所有必要字段
		payload_with_context = {
			**payload,
			'alarm_id': alarm_id,
			'meter_code': meter_code,
			'msg_id': msg_id,
			'alarm_type': alarm_type,
			'rule_name': rule_name,
			'event_source': 'alarm_raised'  # 事件来源标识
		}
		super().__init__(
			event_type=EventType.ALARM_RAISED.value,
			payload=payload_with_context,
			alarm_id=alarm_id,
			msg_id=msg_id,
			meter_code=meter_code,
		)


@dataclass(frozen=True)
class AlarmRecoveredEvent(DomainEvent):
	def __init__(self, alarm_id: int, msg_id: str, meter_code: str, alarm_type: str, rule_name: str = '', **payload: Any):
		"""告警恢复事件

		Args:
			alarm_id: 告警ID
			msg_id: 消息ID
			meter_code: 电表编码
			alarm_type: 告警类型
			rule_name: 规则名称
			**payload: 其他负载数据
		"""
		# 构造完整的payload，确保包含所有必要字段
		payload_with_context = {
			**payload,
			'alarm_id': alarm_id,
			'meter_code': meter_code,
			'msg_id': msg_id,
			'alarm_type': alarm_type,
			'rule_name': rule_name,
			'event_source': 'alarm_recovered'  # 事件来源标识
		}
		super().__init__(
			event_type=EventType.ALARM_RECOVERED.value,
			payload=payload_with_context,
			alarm_id=alarm_id,
			msg_id=msg_id,
			meter_code=meter_code,
		)


@dataclass(frozen=True)
class WorkOrderClosedEvent(DomainEvent):
	def __init__(self, work_order_id: int, alarm_id: int, meter_code: str | None = None, alarm_type: str | None = None, **payload: Any):
		"""工单关闭事件

		Args:
			work_order_id: 工单ID
			alarm_id: 关联的告警ID
			meter_code: 电表编码（可选）
			alarm_type: 告警类型（可选）
			**payload: 其他负载数据
		"""
		# 构造完整的payload，确保包含所有必要字段
		payload_with_context = {
			**payload,
			'alarm_id': alarm_id,
			'work_order_id': work_order_id,
			'event_source': 'work_order_closed'  # 事件来源标识
		}
		# 只有在meter_code有值时才添加
		if meter_code:
			payload_with_context['meter_code'] = meter_code
		# 只有在alarm_type有值时才添加
		if alarm_type:
			payload_with_context['alarm_type'] = alarm_type

		super().__init__(
			event_type=EventType.WORK_ORDER_CLOSED.value,
			payload=payload_with_context,
			alarm_id=alarm_id,
			meter_code=meter_code,
		)
